package com.vois.jack.btmgr.classicbase;

import com.vois.jack.btmgr.common.DeviceRecorderControlInterface;
import com.vois.jack.btmgr.util.Logger;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BtOpusCodedRecorder implements BtRecorderInterface {
    private Logger logger = Logger.getLogger(BtOpusCodedRecorder.class);
    private boolean isStarted;
    private BlockingQueue<byte[]> codedDataQueue;

    @Override
    public void create(int audioSource, int sampleRate) {
        isStarted = false;
        logger.d( "create: audio created");
    }

    @Override
    public void release() {
        stopRecord();
    }

    @Override
    public int getAudioSource() {
        return 0;
    }

    @Override
    public int getSampleRate() {
        return 16000;
    }

    @Override
    public void startRecord() {
        if (!isStarted) {
            isStarted = true;
            codedDataQueue = new ArrayBlockingQueue<>(1000);
        }
    }

    @Override
    public void stopRecord() {
        if (isStarted) {
            codedDataQueue.clear();
            codedDataQueue = null;
            isStarted = false;
        }
    }

    @Override
    public int putRecordData(byte[] rawData, int offset, int rawDataSize) {
        return 0;
    }

    @Override
    public int readRecordData(short[] audioData, int offsetInShort, int sizeInShort) {
        return 0;
    }

    @Override
    public int putEncodedRecordData(byte[] rawData, int offsetInByte, int rawDataSize) {
        int len = 0;
        try {
            if (codedDataQueue != null && isStarted) {
                byte[] data = new byte[rawDataSize];
                System.arraycopy(rawData, offsetInByte, data, 0, rawDataSize);
                codedDataQueue.put(data);
                len = rawDataSize;
            }
        }catch (InterruptedException e) {
            e.printStackTrace();
        }

        return len;
    }

    @Override
    public int getEncodedRecordData(byte[] rawData) {
        int len = 0;
        try {
            if (codedDataQueue != null && isStarted) {
                byte[] data = codedDataQueue.take();
                System.arraycopy(data, 0, rawData, 0, data.length);
                len = data.length;
            }
        }catch (InterruptedException e) {
            e.printStackTrace();
        }

        return len;
    }

    @Override
    public int getAudioSessionId() {
        return 0;
    }

    @Override
    public int getRecordDataType() {
        return ENCODED_RECORD_OPUS_DATA;
    }
}
